package net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    //客户端使用Socket对象来建立连接
    private Socket socket = null;

    public TcpEchoClient(String serverIP,int serverPort) throws IOException {
        //和服务器建立连接，就需要知道服务器在哪
        //此处与UDP客户端差别较大
        socket = new Socket(serverIP,serverPort);
    }

    public void Start(){
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            while(true){
                //1.从控制台读取数据，构成一个请求
                System.out.println("->:");
                String request = scanner.next();
                //2.发送给服务器
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                //这个flush不要忘记，否则可能会导致请求没有发送出去
                printWriter.flush();
                //3.从服务器读取响应
                Scanner respScanner = new Scanner(inputStream);
                String response = respScanner.next();
                //4.把响应显示在界面上
                System.out.println(response);
            }
        } catch (IOException e) {
            e.getStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.Start();
    }
}
